package com.dao;

import com.entity.DvdInfo;
import com.entity.Goods;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description TODO
 * @Author hyl
 * @Date 2022/4/22 10:49
 **/
public class GoodsDaoImpl extends BaseDao implements GoodsDao{

	/**
	 *  购物
	 * @param buyerId 购买者 ==》张三
	 * @param goods 购买的商品
	 * 张三  ==》 购买==》李四===》的商品
	 */
	@Override
	public void buy(Integer buyerId, Goods goods) {

		//(Integer id, String name, Double price, String description, String
		// addTime, Integer isOnSell, Integer typeID, Integer ownerID

		double goodsPrice = goods.getPrice();
		//修改购买商品的用户余额==》扣减  ==》张三 的余额
		String sql = "update user set balance=balance- "+goodsPrice+" where id="+buyerId;

		//出售商品的人==》余额 增加
		sql = "update user set balance=balance + "+goodsPrice+" where id="+goods.getOwnerID();

		//修改商品的主人编号
		sql = "update goods set ownerID="+buyerId+" where id="+goods.getId();

		//添加交易记录id
		sql = "Insert into tradeLog(buyerID,goodsID,sellerID,tradeTime,receiveInfo) " +
				"values("+buyerId+","+goods.getId()+","+goods.getOwnerID()+",now(),'郴州')";

	}

	@Override
	public List<Goods> findByPage(int pageSize,int showSize) {
		List<Goods> list = new ArrayList<Goods>();
		//创建链接
		Connection conn = getConnection();
		//编写sql
		String sql="Select *  from goods " +
				" limit ?,?";
		//创建执行对象
		PreparedStatement psm = null;
		ResultSet rs = null;
		try {
			psm = conn.prepareStatement(sql);
			psm.setInt(1, (pageSize-1)*showSize);
			psm.setInt(2, showSize);
			//执行
			rs = psm.executeQuery();//查询==》返回的是，虚拟表==》sql的运行结果
			//处理返回结果
			while (rs.next()){
				Goods tmp = new Goods();
				tmp.setId(rs.getInt("id"));
				tmp.setName(rs.getString("name"));
				list.add(tmp);
			}
		} catch (SQLException throwables) {
			throwables.printStackTrace();
		}finally {
			closeAll(rs, psm, conn);
		}
		return list;
	}
}
